<?php
/**
 * Created by PhpStorm.
 * User: XiaoBingBy
 * Date: 2017/10/25
 * Time: 11:23
 */
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Exception;
use think\Request;

class Normitem extends Controller
{

    public function index() {
        return $this->fetch();
    }

    /**
     * 所有数据
     * @return \think\response\Json
     */
    public function getList() {
        $sql = '
                SELECT
               CONCAT ("T",t1.id) as id,
               CONCAT ("T",t1.parentnormtarget_id) as pid,
                t1.name,
                (NULL) AS score,
                t1.sort_code AS sort_code,
                (1) AS type
            FROM
                oes_normtarget AS t1
            UNION
                SELECT
                    t2.id,
                    CONCAT ("T", t2.normtarget_id) as pid,
                    t2.name,
                    t2.score,
                    t2.sort_code,
                    (2) AS type
                FROM
                    oes_normitem AS t2
        ';
        $result = DB::query($sql);
        return json($result);
    }

    /**
     * 指标备选项
     * @param Request $request
     * @return \think\response\Json
     */
    public function addNormitem(Request $request) {
        // 获取参数仅包含数组中字段
        $data = $request->only(['name', 'sort_code', 'score', 'normtarget_id']);
        // 添加数据
        $result = DB::name('normitem')->insert($data);
        // 返回数据
        if ($result >= 1) {
            return json(['success'=>true, "msg"=>'添加成功', $result]);
        } else {
            return json(['success'=>false, "msg"=>'添加失败']);
        }
    }

    /**
     * 修改指标备选项
     * @param Request $request
     * @return \think\response\Json
     */
    public function updateNormitem(Request $request) {
        // 获取参数仅包含数组中字段
        $data = $request->only(['id', 'name', 'sort_code', 'score', 'normtarget_id']);
        // 添加数据
        $result = DB::name('normitem')->update($data);
        // 返回数据
        if ($result >= 1) {
            return json(['success'=>true, "msg"=>'修改成功', $result]);
        } else {
            return json(['success'=>false, "msg"=>'修改失败']);
        }
    }

    /**
     * 传入ID获取指标备选项
     * @param $id
     * @return \think\response\Json
     */
    public function getNormitemById($id) {
        $result = DB::name('normitem')->find($id);
        return json($result);
    }

    /**
     * 删除指标备选项
     * @param $id
     * @return \think\response\Json
     */
    public function delete($id) {
        $result = DB::name('normitem')->delete($id);
        if ($result >= 1) {
            return json(['success'=>true, "msg"=>'删除成功']);
        } else {
            return json(['success'=>false, "msg"=>'删除用户不存在']);
        }
    }

}